<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 绑定账号
 *
 * @author      Eden
 * @datetime    2016/12/1 11:40
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Rebind_Model extends API_Model
{
    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
        $this->load->driver('cache');
    }

    /**
     * 主程序
     * @param array $params
     */
    public function run($params = array())
    {
        $send['state'] = false;
        do {
            if (!$this->checkParams($params)) {
                $send['error'] = $this->getError();
                break;
            }

            // 验证码
            if (!$this->checkSms($params)) {
                $send['error'] = '验证码错误';
                break;
            }

            $db = clone($this->db);
            $query = $db->get_where('user', array('phone' => $params['phone']));
            $res = $query->row_array();
            if ($res) {
                $send['error'] = '用户已存在';
                break;
            } else {
                $userDb = clone($this->db);
                $userDb->where(['id' => $params['userId']]);
                $userDb->update('user', ['phone' => $params['phone']]);

                $send['state'] = true;
                $send['data'] = [
                    'msg' => '修改成功'
                ];
            }
        } while(false);
        $this->output->send($send);
    }

    /**
     * 检查 SMS
     * @param $params
     * @return bool
     */
    public function checkSms($params)
    {
        $key = 'API:Member:Rebind:' . $params['phone'];
        $cacheData = $this->cache->redis->get($key);
        if ($cacheData) {
            $code = value($cacheData, 'code');
            if ($code == $params['code']) {
                $this->cache->redis->delete($key);
                return true;
            }
        } else {
            $this->output->send(array(
                'state' => false,
                'error' => '验证码已失效'
            ));
        }
        return false;
    }

    /**
     * 检查参数
     * @param $params
     * @return bool
     */
    private function checkParams($params)
    {
        if ($this->input->method(true) !== 'POST') {
            $this->setError('非法请求');
            return false;
        }

        if (empty($params['phone']) || empty($params['code']) || empty($params['userId'])) {
            $this->setError('参数错误');
            return false;
        }

        return true;
    }

}
